import { Form, Space, Button, type FormInstance, Row, Col } from 'antd'
import './index.less'
import { Fragment, ReactNode, CSSProperties, useState, useLayoutEffect } from 'react'
import getComponents from './ComponentType'
import { useForm } from 'antd/es/form/Form'
import { DownOutlined, UpOutlined } from '@ant-design/icons'

interface IProps {
  form?: FormInstance
  searchConfig: IItemArray[]
  onFinish: (value: any) => void
  onReset: () => void
  style?: CSSProperties
}

type IType =
  | 'Custom'
  | 'Input'
  | 'TreeSelect'
  | 'Search'
  | 'Password'
  | 'TextArea'
  | 'Upload'
  | 'InputNumber'
  | 'Select'
  | 'Switch'
  | 'DatePicker'
  | 'RangePicker'
  | 'Cascader'
  | 'Radio'
  | 'Transfer'
export interface IItemArray {
  name: string
  label: string
  type: IType
  option?: IOption[]
  config?: object
  valuePropName?: string
  checked?: boolean
  placeholder?: string
  slot?: ReactNode
  [k: string]: any
}

interface IOption {
  label: string | number
  value: string | number | any
  disabled?: boolean
  [k: string]: any
}

export default function SearchFormComponent(props: IProps) {
  const [form] = useForm()
  const maxSpan = 24
  const slicedNum = 2
  const grid = { xs: 24, sm: 24, md: 12, lg: 8, xl: 8, xxl: 6 }
  const [isFold, setIsFold] = useState(true) //默认是折叠状态
  const [currentSpan, setCurrentSpan] = useState(8) //默认一行展示24/8=3个
  const reCalcHeight = () => {
    if (window.innerWidth < 768) {
      setCurrentSpan(24)
    } else if (window.innerWidth >= 768 && window.innerWidth < 992) {
      if (isFold) {
        if (props.searchConfig.slice(0, slicedNum).length % (maxSpan / grid.md) === 0) setCurrentSpan(24)
        if (props.searchConfig.slice(0, slicedNum).length % (maxSpan / grid.md) === 1) setCurrentSpan(12)
      } else {
        if (props.searchConfig.length % (maxSpan / grid.md) === 0) setCurrentSpan(24)
        if (props.searchConfig.length % (maxSpan / grid.md) === 1) setCurrentSpan(12)
      }
    } else if (window.innerWidth >= 992 && window.innerWidth < 1600) {
      if (isFold) {
        if (props.searchConfig.slice(0, slicedNum).length % (maxSpan / grid.lg) === 0) setCurrentSpan(24)
        if (props.searchConfig.slice(0, slicedNum).length % (maxSpan / grid.lg) === 1) setCurrentSpan(16)
        if (props.searchConfig.slice(0, slicedNum).length % (maxSpan / grid.lg) === 2) setCurrentSpan(8)
      } else {
        if (props.searchConfig.length % (maxSpan / grid.lg) === 0) setCurrentSpan(24)
        if (props.searchConfig.length % (maxSpan / grid.lg) === 1) setCurrentSpan(16)
        if (props.searchConfig.length % (maxSpan / grid.lg) === 2) setCurrentSpan(8)
      }
    } else {
      if (isFold) {
        if (props.searchConfig.slice(0, slicedNum).length % (maxSpan / grid.xxl) === 0) setCurrentSpan(24)
        if (props.searchConfig.slice(0, slicedNum).length % (maxSpan / grid.xxl) === 1) setCurrentSpan(18)
        if (props.searchConfig.slice(0, slicedNum).length % (maxSpan / grid.xxl) === 2) setCurrentSpan(12)
      } else {
        if (props.searchConfig.length % (maxSpan / grid.xxl) === 0) setCurrentSpan(24)
        if (props.searchConfig.length % (maxSpan / grid.xxl) === 1) setCurrentSpan(18)
        if (props.searchConfig.length % (maxSpan / grid.xxl) === 2) setCurrentSpan(12)
        if (props.searchConfig.length % (maxSpan / grid.xxl) === 3) setCurrentSpan(6)
      }
    }
  }
  // 解决页面按钮位置的闪烁
  useLayoutEffect(() => {
    reCalcHeight()
    window.addEventListener('resize', debounce(reCalcHeight, 300))
    return () => {
      window.removeEventListener('resize', reCalcHeight)
    }
  }, [isFold])

  function isPass() {
    const formIns = props.form ? props.form : form
    const newValues: Record<string, string | number> = {}
    formIns.validateFields().then((values) => {
      Object.keys(values).forEach((key) => {
        newValues[key] = values[key] === undefined ? '' : values[key]
      })
      props.onFinish(newValues)
    })
  }

  function handleClickFold() {
    setIsFold(!isFold)
  }

  function debounce(fn: any, delay: number) {
    let timer: NodeJS.Timeout
    return (...set: any) => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        fn(...set)
      }, delay)
    }
  }

  return (
    <div className="search_form_wrap">
      <Form
        form={props.form ? props.form : form}
        labelAlign="right"
        layout="inline"
        labelWrap={true}
        onFinish={props.onFinish}
      >
        <Row gutter={[10, 10]}>
          {isFold
            ? props.searchConfig.slice(0, slicedNum)?.map((item, index) => {
                return (
                  <Col {...grid} key={index}>
                    <Fragment>
                      <Form.Item {...item}>{item ? getComponents(item) : null}</Form.Item>
                    </Fragment>
                  </Col>
                )
              })
            : props.searchConfig?.map((item, index) => {
                return (
                  <Col {...grid} key={index}>
                    <Fragment>
                      <Form.Item {...item}>{item ? getComponents(item) : null}</Form.Item>
                    </Fragment>
                  </Col>
                )
              })}
          <Col span={currentSpan}>
            <div style={{ textAlign: 'right' }}>
              <Space>
                <Button onClick={props.onReset}>重置</Button>
                <Button type="primary" onClick={isPass}>
                  查询
                </Button>
                {props?.searchConfig?.length > 2 ? (
                  <Button type="link" onClick={handleClickFold}>
                    {isFold ? '展开' : '收起'}
                    {isFold ? <DownOutlined /> : <UpOutlined />}
                  </Button>
                ) : null}
              </Space>
            </div>
          </Col>
        </Row>
      </Form>
    </div>
  )
}
